<template>
  <el-dialog title="编辑团队信息" v-model="dialogVisible" width="500px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <!-- 团队名称 -->
      <el-form-item label="团队名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入团队名称"></el-input>
      </el-form-item>

      <!-- 团队头像 -->
      <el-form-item label="团队头像">
        <el-upload class="avatar-uploader" action="http://nocat.life:3012/images/upload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img class="avatar" v-if="form.avatar" :src="form.avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <span class="upload-text">+上传头像</span>
      </el-form-item>

      <!-- 所属机构（单选下拉） -->
      <el-form-item label="所属机构" prop="_id">
        <el-select v-model="form._id" placeholder="请选择" clearable>
          <el-option v-for="item in orgOptions" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>

      <!-- 团队标签（多选下拉） -->
      <el-form-item label="团队标签" prop="tags">
        <el-select v-model="form.tags" multiple placeholder="请选择" clearable>
          <el-option v-for="item in tagOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { searchOrganizationsApi } from '../../api/organizations';


// 接收父组件参数
const props = defineProps({
  visible: Boolean,          // 弹窗显示状态
  teamInfo: {                // 团队初始数据
    type: Object,
    default: () => ({
      name: '',
      avatar: '',
      _id: '',
      tags: []
    })
  },
  tagOptions: {              // 团队标签下拉选项
    type: Array,
    default: () => []
  }
});

// 子组件自主维护机构下拉选项
const orgOptions = ref([]);

// 表单引用（用于校验）
const formRef = ref(null);

// 向父组件发射事件
const emit = defineEmits(['update:visible', 'save']);

// 弹窗显示状态
const dialogVisible = ref(props.visible);
watch(props, (newProps) => {
  dialogVisible.value = newProps.visible;
  // 弹窗打开时自动加载机构数据
  if (newProps.visible) {
    searchOrganization();
  }
});

// 表单数据
const form = ref({
  name: '',
  avatar: '',
  _id: '',
  tags: []
});

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入团队名称', trigger: 'blur' }
  ],
  _id: [
    { required: true, message: '请选择所属机构', trigger: 'change' }
  ]
};

// 头像上传相关
const fileList = ref([]); // 上传文件列表（用于回显已上传头像）

// 上传成功回调（更新头像URL）
const handleAvatarSuccess = (res) => {
  if (res.code == 200) {
    form.value.avatar = res.data;
  }
};

// 上传前校验（格式、大小）
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) ElMessage.error('仅支持图片格式！');
  if (!isLt2M) ElMessage.error('图片大小不能超过 2MB！');
  return isImage && isLt2M;
};

// 初始化表单（监听父组件传入的 teamInfo）
watch(props.teamInfo, (newInfo) => {
  form.value.name = newInfo?.name || '';
  form.value.avatar = newInfo?.avatar || '';
  form.value._id = newInfo?._id || '';
  form.value.tags = newInfo?.tags || [];
  // 回显已上传的头像到 fileList
  fileList.value = newInfo?.avatar ? [{ url: newInfo.avatar }] : [];
}, { immediate: true });

// 关闭弹窗（重置表单）
const handleClose = () => {
  emit('update:visible', false); // 通知父组件关闭
  // 重置表单数据
  form.value = { name: '', avatar: '', _id: '', tags: [] };
  fileList.value = [];
};

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit('save', form.value);
      handleClose();
    } else {
      ElMessage.error('表单校验失败，请检查！');
    }
  });
};

// 获取所有机构
function searchOrganization() {
  searchOrganizationsApi()
    .then(res => {
      if (res.code === 200) {
        console.log(res.data);
        if (Array.isArray(res.data.rows)) {
          orgOptions.value = res.data.rows.map(item => ({
            value: item._id,   // 选值：用机构 ID
            label: item.name  // 显示：用机构名称
          }));
        } else {
          ElMessage.error('机构数据格式错误（需返回数组）');
        }
      } else {
        ElMessage.error(`获取机构失败：${res.msg || '未知错误'}`);
      }
    })
    .catch(err => {
      ElMessage.error('网络错误：' + err.message);
      console.error('机构数据请求失败：', err);
    });
}
</script>

<style scoped>
.avatar-uploader {
  width: 50px;
  height: 50px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
}

.upload-text {
  margin-left: 10px;
  color: rgba(41, 132, 248, 1);
}

.avatar-uploader-icon {
  color: #8c939d;
  width: 50px;
  height: 50px;

}

.avatar {
  width: 50px;
  height: 50px;
}


.dialog-footer {
  text-align: right;
}

.el-form .el-form-item {
  margin: 25px;
}
</style>